import { authRequest }          from "../../api/request";
import { apiRequest, mergeApi } from "../../assets/fetch";
import { mergeOf }              from '../../assets/simple';

const defaultValue = {
    deleteModelShow   : false,
    deleteModelLoading: false,
};

export default {
    namespaced: true,
    state     : {
        users: [],
        meta : {},
    },
    mutations : {
        users(state, data) {
            state.users = data;
        },
        meta(state, meta) {
            state.meta = meta;
        },
        page(state, page) {
            state.page = page;
        },
        pageIndex(state, value) {
            state.pageIndex = value;
        },
        changeUserForIndex(state, data) {
            if (!state.users) {
                return;
            }
            let index = state.users.findIndex((item) => item.id === data.id);

            if (~index) {
                state.users.splice(index, 1, mergeOf(defaultValue, data));
            }
        }
    },
    actions   : {
        async switchSelfStatus({ state }, status) {
            return await apiRequest('USER_STATUS', { data: { status } });
        },
        async userForType(_, type) {
            return await apiRequest('USER_TYPE_LIST', { data: { type } });
        },
        async getUsers({ commit, state }, {
            page,
            pageSize
        }) {
            let res = await apiRequest('USER_INDEX', {
                data: {
                    page,
                    pageindex: pageSize,
                }
            });

            if (res.result) {
                commit('users', res.data.data);
                commit('meta', res.data.meta);
            }

            return res;
        },
        async createUser(_, data) {
            let res = await apiRequest('USER_CREATE', { data });

            return res;
        },
        async updateUser({ commit }, data) {
            let res = await  apiRequest('USER_UPDATE', { data }, data.id);

            if (res.result) {
                let user = res.data;
                commit('changeUserForIndex', user);
            }

            return res;
        },
        async deleteUser({ commit }, ids) {
            let options = mergeApi('USER_DELETE');
            options.url = `${options.url}${ids}`;
            return await authRequest(options);

        }
    }
}
